package com.xhwl.centiotdata.config;

import com.xhwl.centiotdata.integration.IntegrationZoneException;
import com.xhwl.common.enums.CodeEnum;
import com.xhwl.common.exception.ApplicationException;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.exception.DataException;
import com.xhwl.common.pojo.ResultJson;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @Author: luyi
 * @Description:
 * @Date: Create in 14:32 2021/1/6
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    public ResultJson httpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException ex, HttpServletRequest request) {
        log.error("HTTP请求方式不正确：【{}】, 请求地址: 【{}】, 请求query: 【{}】",
                ex.getMessage(), request.getRequestURL(), request.getQueryString());
        return ResultJson.fail(ex.getMessage());
    }

    @ExceptionHandler(value = BusinessException.class)
    public ResultJson businessException(BusinessException be){
        log.error("业务异常: 【{}】", be.getMessage());
        return ResultJson.fail(CodeEnum.BUSINESS_EXCEPTION.code, CodeEnum.BUSINESS_EXCEPTION.description);
    }

    @ExceptionHandler(value = DataException.class)
    public ResultJson dataException(DataException be){
        log.error("数据异常: 【{}】", be.getMessage());
        return ResultJson.fail(CodeEnum.DATA_EXCEPTION.code, CodeEnum.DATA_EXCEPTION.description);
    }

    @ExceptionHandler(value = IntegrationZoneException.class)
    public ResultJson integrationException(IntegrationZoneException exception){
        return ResultJson.fail(CodeEnum.DATA_EXCEPTION.code, exception.getMessage());
    }

    @ExceptionHandler(value = ApplicationException.class)
    public ResultJson dataException(ApplicationException be){
        log.error("应用异常: 【{}】", be.getMessage());
        return ResultJson.fail(CodeEnum.APP_EXCEPTION.code, CodeEnum.APP_EXCEPTION.description);
    }

    @ExceptionHandler(value = RuntimeException.class)
    public ResultJson dataException(RuntimeException be){
        log.error("应用异常: 【{}】", be.getMessage());
        be.printStackTrace();
        return ResultJson.fail(CodeEnum.APP_EXCEPTION.code, CodeEnum.APP_EXCEPTION.description);
    }

}
